const fs = require('fs');
const http = require('http');

const server = http.createServer();

server.on('request', (req, res) => {
  console.log(req.url); // /index.html
  if (req.url === '/') req.url = '/index.html';
  let filename = './view' + req.url;   // ./view/index.html
  // 判断文件是否存在
  fs.access(filename, err => {
    if (err) {
      // 说明文件不存在
      res.statusCode = 404;
      res.setHeader('Content-Type', 'text/plain; charset=utf-8');
      res.end('你请求的文件不存在');
    } else {
      // 说明文件存在
      fs.readFile(filename, (e, data) => {
        if (e) throw e;
        res.end(data);
      });
    }
  })
})

server.listen(4000, () => console.log('启动了'))